<template>
	<view class="container" :style="{background: uploadFail ? '#fff' : ''}">
		<u-navbar title="证件照·选择上传" bgColor="transparent" :placeholder="true" :autoBack="true" />
		<block v-if="!uploadFail">
			<view class="show-img">
				<image src="@/static/img/id-card-img01.png" mode="aspectFit"></image>
			</view>
			<view class="notice">
				拍照须知
			</view>
			<view class="require">
				<view class="require-item">
					<image class="icon" src="@/static/img/id-card-icon01.png" mode="aspectFit"></image>
					<text class="txt">头部摆正</text>
				</view>
				<view class="require-item">
					<image class="icon" src="@/static/img/id-card-icon01.png" mode="aspectFit"></image>
					<text class="txt">双肩齐全</text>
				</view>
				<view class="require-item">
					<image class="icon" src="@/static/img/id-card-icon01.png" mode="aspectFit"></image>
					<text class="txt">光线充足</text>
				</view>
			</view>
			<view class="upload-type">
				<view class="btn" @click="chooseImgFromAlbum('album')">
					从相册选择照片
				</view>
				<view class="btn" @click="chooseImgFromWx">
					从微信选择照片
				</view>
				<view class="btn" @click="chooseImgFromAlbum('camera')">
					手机拍照
				</view>
			</view>
		</block>
		<block v-else>
			<view class="fail-preview">
				<image class="fail-img" :src="failImg"></image>
				<view class="fail-detail">
					<view class="name">
						<span>{{failDetail.length}}</span>项检测不通过
					</view>
					<view class="ctn" v-for="(item, index) in failDetail" :key="index">
						<image src="@/static/img/close01.png"></image>
						<text>{{item.param_message}}</text>
					</view>
				</view>
			</view>
			<view class="reference-title">
				请参考标准照片重新选择照片
			</view>
			<view class="reference-ctn">
				<image class="left" src="@/static/img/id-card-img01.png"></image>
				<view class="right">
					<view class="reference-ctn-item">
						<image class="icon" src="@/static/img/id-card-icon01.png" mode="aspectFit"></image>
						<text>头部摆正</text>
					</view>
					<view class="reference-ctn-item">
						<image class="icon" src="@/static/img/id-card-icon01.png" mode="aspectFit"></image>
						<text>双肩齐全</text>
					</view>
					<view class="reference-ctn-item">
						<image class="icon" src="@/static/img/id-card-icon01.png" mode="aspectFit"></image>
						<text>光线充足</text>
					</view>
				</view>
			</view>
			<view class="choose-again" @click="uploadFail = false">
				重新选择照片
			</view>
		</block>
	</view>
</template>

<script>
	import {
		toPromise,
		uploadFile
	} from '@/utils/util';
	import {
		ID_PHOTO_API,
		ID_PHOTO_KEY,
	} from '@/config/request.js'
	import {
		rejects
	} from 'assert';
	import {
		IdPhotoApi
	} from '@/api';
	export default {
		data() {
			return {
				uploadFail: false,
				// 检测不通过的规则
				failDetail: [],
				// 检测不通过图片
				failImg: '',
				id: 0,
				disabled: false,
			};
		},
		onLoad({
			id
		}) {
			this.id = Number(id)
			this.getSizeDetail()
		},
		methods: {
			/**
			 * 获取后台尺寸详细
			 */
			getSizeDetail() {
				IdPhotoApi.getDocumentSizeConfigsList({
						id: this.id
					})
					.then(res => {
						let data = res.result
						data.configs = data.configs.map(item => {
							let configs = {
								...item,
								config_json: JSON.parse(item.config_json)
							}
							configs.config_json.background_color = JSON.parse(JSON.parse(item.config_json).background_color)
							return configs
						})
						this.$store.commit('idPhoto/updateSizeList', data)
					})
					.catch(err => {
						this.disabled = true
						this.$showToast(err.msg)
					})
			},
			/** 
			 * 从相册选择照片
			 * @param {String} sourceType	album 从相册选图，camera 使用相机
			 */
			async chooseImgFromAlbum(sourceType = 'album') {
				if (this.disabled)
					return
				try {
					this.$showLoading({
						title: '选择中'
					})
					const chooseRes = await toPromise(uni.chooseImage, {
						count: 1,
						sizeType: 'original',
						sourceType: [sourceType]
					}).catch(err => err)
					uni.hideLoading()
					if (!chooseRes.tempFilePaths?.length) //取消选择
						return
					await this._handlePhoto(chooseRes.tempFilePaths[0])
				} catch (err) {
					uni.hideLoading()
					this.$showToast(err.message || err.msg)
				}
			},
			/** 
			 * 从微信记录选择照片
			 */
			async chooseImgFromWx() {
				if (this.disabled)
					return
				try {
					this.$showLoading({
						title: '选择中'
					})
					const selectRes = await toPromise(wx.chooseMessageFile, {
						count: 1,
						type: 'image',
					})
					uni.hideLoading()
					if (!selectRes.tempFiles?.length) //取消选择
						return
					await this._handlePhoto(selectRes.tempFiles[0].path)
				} catch (err) {
					uni.hideLoading()
					this.$showToast(err?.message || err?.msg)
				}
			},
			/**
			 * 检测制作证件照
			 */
			_handlePhoto(filePath) {
				return new Promise(async (resolve, reject) => {
					try {
						this.$showLoading({
							title: '检测并制作中'
						})
						// 转换 base64
						const imgDetail = wx.getFileSystemManager().readFileSync(filePath, 'base64')
						let fileList = []
						for (const item of this.$store.state.idPhoto.sizeList.configs) {
							const res = await this.cutCheckPic(imgDetail, Number(item.config))
							if (res.code !== 200)
								return reject(new Error(res.error))
							if (res?.not_check_result.length) {
								// 检测不通过
								this.failDetail = res.not_check_result
								this.uploadFail = true // 重新选择
								this.failImg = res.result?.img_wm_url_list[0] // 失败图
							} else {
								// 检测通过
								console.log('制作结果= ', res.result);
								fileList.push(res.result)
							}
						}
						this.$store.commit('idPhoto/updateUserIdPhoto', fileList)
						this.$navTo('pages/indexs/id_photo/edit_preview')
						uni.hideLoading()
						return resolve(fileList)
					} catch (err) {
						console.log('制作失败= ', err);
						uni.hideLoading()
						return reject(err)
					}
				})
			},
			/** 
			 * 制作并检测证件照（处理单张）
			 * @param {String} file base64格式
			 * @param {Number} specId 规格id
			 */
			cutCheckPic(fileUrl, specId) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: ID_PHOTO_API + 'cut_check_pic',
						method: 'POST',
						data: {
							file: fileUrl, // detail param (http://dev.id-photo-verify.com/doc.html) 
							spec_id: specId,
							app_key: ID_PHOTO_KEY,
						},
						success: (res) => {
							if (res.data.code !== 200)
								return reject(new Error(res.data.error))
							resolve(res.data)
						},
						fail: (err) => reject(err)
					})
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		width: 100vw;
		height: 100vh;
		background: linear-gradient(180deg, #feeadb 0%, #ffffff00 100%);
	}

	.show-img {
		position: relative;
		margin: 110rpx auto 0;
		width: 302rpx;
		height: 414rpx;
		background: url('@/static/img/id-card-bg.png') no-repeat;
		background-size: cover;

		>image {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			width: 270rpx;
			height: 382rpx;
			z-index: 2;
		}
	}

	.notice {
		margin: 60rpx auto 0;
		width: 460rpx;
		height: 60rpx;
		line-height: 60rpx;
		background: linear-gradient(90deg, #fcf7f4 0%, #feebdc 50%, #fcf7f3 100%);
		color: #000000;
		text-align: center;
		font-size: 28rpx;
	}

	.require {
		display: flex;
		justify-content: space-between;
		margin-top: 60rpx;
		padding: 0 120rpx;
	}

	.require-item {
		display: flex;
		align-items: center;

		.icon {
			width: 24rpx;
			height: 24rpx;
		}

		.txt {
			margin-left: 10rpx;
			color: #535353;
			font-size: 24rpx;
		}
	}

	.upload-type {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin: 100rpx 0 0;
		text-align: center;

		.btn {
			box-sizing: border-box;
			margin-top: 30rpx;
			width: 590rpx;
			height: 70rpx;
			line-height: 70rpx;
			border-radius: 10rpx;
			border: 2rpx solid #dbdbdb;
			background-color: #fff;
			color: #848484;
			text-align: center;
			font-size: 24rpx;

			&:first-child {
				margin-top: 0;
			}

			&:last-child {
				border: none;
				background: $gradient-bg-color;
				color: #FFFFFF;
			}
		}
	}

	.fail-preview {
		display: flex;
		align-items: center;
		margin-top: 130rpx;
		padding: 0 80rpx;
	}

	.fail-img {
		width: 234rpx;
		height: 308rpx;
	}

	.fail-detail {
		flex: 1;
		margin-left: 40rpx;

		.name {
			color: #0C0C0C;
			font-size: 28rpx;

			span {
				color: #FF0000;
			}
		}

		.ctn {
			display: flex;
			align-items: flex-start;
			margin-top: 20rpx;

			image {
				margin-top: 6rpx;
				width: 20rpx;
				height: 20rpx;
			}

			text {
				flex: 1;
				margin-left: 6rpx;
				color: #5b5b5b;
				font-size: 24rpx;
			}

			&:first-child {
				margin-top: 40rpx;
			}
		}
	}

	.reference-title {
		margin-top: 160rpx;
		color: #000000;
		text-align: center;
		font-size: 28rpx;
	}

	.reference-ctn {
		display: flex;
		justify-content: space-between;
		margin-top: 80rpx;
		padding: 0 168rpx;

		.left {
			box-sizing: border-box;
			width: 184rpx;
			height: 260rpx;
			border: 1rpx dashed #afb0b2;
		}
	}

	.reference-ctn-item {
		display: flex;
		align-items: center;
		margin-top: 40rpx;

		.icon {
			width: 24rpx;
			height: 24rpx;
		}

		text {
			margin-left: 10rpx;
			color: #535353;
			font-size: 24rpx;
		}

		&:first-child {
			margin-top: 56rpx;
		}
	}

	.choose-again {
		margin: 100rpx auto 0;
		width: 590rpx;
		height: 70rpx;
		line-height: 70rpx;
		border-radius: 10rpx;
		background: $gradient-bg-color;
		color: #ffffff;
		text-align: center;
		font-size: 24rpx;
	}
</style>